package day6.Component;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class TestCardLayout2 extends JFrame {

	public TestCardLayout2(String title) {
		this.setTitle(title);
		this.setSize(400, 500);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		initComponent();
		
		// 放到最后显示窗口
		this.setVisible(true);
	}
	// 初始化
	private void initComponent() {
		//北部四个按钮
		JPanel northJPanel = new JPanel();//默认流式布局
		JButton b1 = new JButton("黄");
		JButton b2 = new JButton("灰");
		JButton b3 = new JButton("绿");
		JButton b4 = new JButton("粉");
		//按钮需要绑定监听器，通过事件切换卡片
		JButton[] btns = new JButton[4];
		btns[0] = b1;
		btns[1] = b2;
		btns[2] = b3;
		btns[3] = b4;
		northJPanel.add(b1);
		northJPanel.add(b2);
		northJPanel.add(b3);
		northJPanel.add(b4);
		
		//中间四个卡片
		JPanel centerJPanel = new JPanel();   // 卡片布局
		centerJPanel.setLayout(new CardLayout());
		for (int i = 0; i < btns.length; i++) {
			btns[i].addMouseListener(new MouseAdapter() {
				//切换卡片逻辑
				
				@Override
				public void mouseClicked(MouseEvent e) {
					//谁拿的 拿到按钮上的文字 show()
					//事件源
					JButton btn = (JButton) e.getSource();
					//按钮上的文字
					String cardName = btn.getText();
					//拿到卡片布局管理器  显示该卡片名字
					CardLayout card = (CardLayout) centerJPanel.getLayout();
					card.show(centerJPanel, cardName);
					
				}
				
			});
		}
		JPanel p1 = new JPanel();
		p1.setBackground(Color.yellow);
		JPanel p2 = new JPanel();
		p2.setBackground(Color.gray);
		JPanel p3 = new JPanel();
		p3.setBackground(Color.green);
		JPanel p4 = new JPanel();
		p4.setBackground(Color.pink);
		centerJPanel.add("黄",p1);
		centerJPanel.add("灰",p2);
		centerJPanel.add("绿",p3);
		centerJPanel.add("粉",p4);
	   
		this.add(northJPanel,BorderLayout.NORTH);
		this.add(centerJPanel);
		
		
		
	}

	public static void main(String[] args) {
		new TestCardLayout2("卡片布局配合监听器");
	}

}


